package com.base.cn.platform.os.common.utils.sms;

import com.base.cn.platform.os.common.utils.InputStreamUtil;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
 * 创世云短信发送工具类
 *
 * @author s.li
 * @create 2018-01-02-13:48
 */
public class CSYSmsSendUtils {
    private static Logger logger = LoggerFactory.getLogger(CSYSmsSendUtils.class);
    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    /*public static void main(String[] args){
        sendMessage("18911893513","您的注册验证码是123456，请在30分钟内输入，如非本人请忽略本短信。",
                "ca5d4c5273b1e0ea6f52a172c98f5ab5",
                "pVAWnocQgQqIqypC",
                "fVWZqgilQBwDjyxMdd3CtfRDzECDcGlx");
    }*/

    public static boolean sendMessage(String mobile,String context,String appKey,String appId,String appSecret){
        String getTokenData = getToken(appId,appSecret);
        logger.info("----------getTokenData:"+getTokenData);
        JSONObject tokenJson = new JSONObject(getTokenData);
        int status = tokenJson.getInt("status");
        String info = tokenJson.getString("info");
        String access_token = "";
        if(status == 1){
            JSONObject data = tokenJson.getJSONObject("data");
            access_token = data.getString("access_token");
            int expires_in = data.getInt("expires_in");//access_token的生命周期，单位是秒数。过期之后要重新获取
            logger.info("--------expires_in:"+expires_in);
            String sendSmsResult = sendSms(appKey,access_token,mobile,context);
            logger.info("----------sendSmsResult:"+sendSmsResult);
            if(StringUtils.isNotEmpty(sendSmsResult)){
                Map<String,String> resultMap = gson.fromJson(sendSmsResult,new TypeToken<Map<String,String>>(){}.getType());
                String code = resultMap.get("code");
                if(StringUtils.isNotEmpty(code) && code.equals("1000")){
                    return true;//======发送成功
                }
            }
        }
        return false;//发送失败
    }

    private static String getToken(String appId,String appSecret) {
        try {
            URL url = new URL("https://api.chuangcache.com/OAuth/authorize");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type","application/json");
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            JSONObject obj = new JSONObject();
            obj.put("appid", appId);//填写appkey (客服人员会给出)
            obj.put("appsecret",appSecret);//填写appsecret(客服人员会给出)
            obj.put("grant_type", "client_credentials");
            out.writeBytes(obj.toString());
            out.flush();
            out.close();

            InputStream inStream = conn.getInputStream();
            return new String(InputStreamUtil.readInputStream(inStream), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String addSmsService(String access_token) {
        OutputStreamWriter out = null;
        try {
            URL url = new URL("http://sms.chuangcache.com/api/app/addSms");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject obj = new JSONObject();
            obj.put("access_token", access_token);
            obj.put("name", "测试-创世云");
            obj.put("sign", "创世云");//每个服务对应一个签名，签名不可更改
            obj.put("url", "");
            obj.put("time", System.currentTimeMillis() + "");

            out = new OutputStreamWriter(
                    conn.getOutputStream());
            out.write(obj.toString());
            out.flush();

            InputStream inStream = conn.getInputStream();
            return new String(InputStreamUtil.readInputStream(inStream), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sendSms(String app_key,String access_token,String mobile,String context) {
        try {
            URL url = new URL("http://sms.chuangcache.com/api/sms/ordinary");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type","application/json;charset=UTF-8;");

            JSONObject obj = new JSONObject();
            obj.put("access_token", access_token);
            obj.put("app_key", app_key);
            obj.put("mobile", mobile);//手机号码
            obj.put("content", context);//发送内容
            obj.put("time", String.valueOf(System.currentTimeMillis()));
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(obj.toString().getBytes());
            logger.info("===================发送的短信内容："+obj.toString());
            out.flush();
            out.close();
            InputStream inStream = conn.getInputStream();
            return new String(InputStreamUtil.readInputStream(inStream), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
